package com.yu.aspect;

import com.alibaba.fastjson.JSON;
import com.yu.dao.OperateLogMapper;
import com.yu.pojo.OperateLog;
import com.yu.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author 路亚
 * @version 0.1
 * @className Ascept
 * @description
 * @date 2024/10/11 16:29
 * @since jdk11
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;
    @Pointcut("@annotation(com.yu.annotation.Log)")
    public void pt(){}

    @Around("pt()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
//        TODO：1.当前登录员工的id
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer id = (Integer) claims.get("id");

//        TODO:3.操作类名
        String className = joinPoint.getTarget().getClass().getName();

//        TODO:4.方法名
        String methodName = joinPoint.getSignature().getName();

//        TODO:5.参数
        Object[] args = joinPoint.getArgs();
        String argsStr = Arrays.toString(args);

//        TODO:6.返回值
        long beginTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long time = endTime - beginTime;
        String jsonStr = JSON.toJSONString(result);

        OperateLog operateLog = new OperateLog(null,id, LocalDateTime.now(),className,methodName,argsStr,jsonStr,time);

        operateLogMapper.insert(operateLog);
        return result;
    }
}
